<template>
  <div class="login">
    <!-- 登录页头部 -->
    <div class="login-header">
      <div class="flex-y-center">
        <el-switch
          v-model="isDark"
          inline-prompt
          active-icon="Moon"
          inactive-icon="Sunny"
          @change="toggleTheme"
        />
        <lang-select class="ml-2 cursor-pointer" />
      </div>
    </div>

    <!-- 登录页内容 -->
    <div class="login-content">
      <div class="login-img">
        <el-image :src="loginImage" style="width: 210px" />
      </div>
      <div class="login-form">
        <el-form
          ref="forgotFormRef"
          :model="userForgotData"
          :rules="loginRules"
          @validate="onValidate"
        >
          <div class="form-title">
            <h2>重置密码</h2>
          </div>

          <!-- 用户名 -->
          <el-form-item prop="username">
            <div class="input-wrapper">
              <el-icon class="mx-2">
                <User />
              </el-icon>
              <el-input
                ref="username"
                v-model="userForgotData.username"
                :placeholder="$t('login.username')"
                name="username"
                size="large"
                class="h-[48px]"
              />
            </div>
          </el-form-item>

          <!-- 密码 -->
          <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
            <el-form-item prop="password">
              <div class="input-wrapper">
                <el-icon class="mx-2">
                  <Lock />
                </el-icon>
                <el-input
                  v-model="userForgotData.password"
                  :placeholder="$t('login.password')"
                  type="password"
                  name="password"
                  size="large"
                  class="h-[48px] pr-2"
                  show-password
                  @keyup="checkCapslock"
                />
              </div>
            </el-form-item>
          </el-tooltip>

          <!-- 确认密码 -->
          <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
            <el-form-item prop="password_repeat">
              <div class="input-wrapper">
                <el-icon class="mx-2">
                  <Lock />
                </el-icon>
                <el-input
                  v-model="userForgotData.password_repeat"
                  placeholder="确认密码"
                  type="password"
                  name="password_repeat"
                  size="large"
                  class="h-[48px] pr-2"
                  show-password
                  @keyup="checkCapslock"
                />
              </div>
            </el-form-item>
          </el-tooltip>

          <!-- 邮箱 -->
          <el-form-item prop="email">
            <div class="input-wrapper">
              <el-icon class="mx-2">
                <Message />
              </el-icon>
              <el-input
                v-model="userForgotData.email"
                placeholder="电子邮箱地址"
                type="text"
                name="email"
                size="large"
                class="h-[48px] pr-2"
              />
            </div>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="code">
            <div class="input-wrapper">
              <svg-icon icon-class="captcha" class="mx-2" />
              <el-input
                v-model="userForgotData.code"
                auto-complete="off"
                size="large"
                class="flex-1"
                :placeholder="$t('login.captchaCode')"
              />

              <el-button
                class="register-email-button"
                @click="validateEmail"
                :disabled="!isEmailValid || emailCountdown > 0"
              >
                {{ emailCountdown > 0 ? "剩余" + emailCountdown + "秒" : "获取验证码" }}
              </el-button>
            </div>
          </el-form-item>

          <div class="flex-x-between w-full py-1">
            <el-link type="primary" href="/login">已有帐号,点此登录</el-link>

            <el-link type="primary" href="/register">没有帐号？ 点此注册</el-link>
          </div>
          <!-- 登录按钮 -->
          <el-button
            :loading="loading"
            type="primary"
            size="large"
            class="w-full"
            @click.prevent="handleForgotSubmit"
          >
            立即重置
          </el-button>
        </el-form>
      </div>
    </div>

    <!-- 登录页底部 -->
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { LocationQuery, useRoute } from "vue-router";

import AuthAPI, { type LoginData } from "@/api/auth";
import router from "@/router";

import type { FormInstance } from "element-plus";

import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";

import { useSettingsStore, useUserStore, useDictStore } from "@/store";
import UserAPI, { type UserForgotForm } from "@/api/system/user";

const userStore = useUserStore();
const settingsStore = useSettingsStore();
const dictStore = useDictStore();

const route = useRoute();
const { t } = useI18n();
const forgotFormRef = ref<FormInstance>();

const isDark = ref(settingsStore.theme === ThemeEnum.DARK); // 是否暗黑模式
const loading = ref(false); // 按钮 loading 状态
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串

const isEmailValid = ref(false);
const emailCountdown = ref(0);
const emailTimer = ref<NodeJS.Timeout | null>(null);
const onValidate = (prop: any, isValid: boolean) => {
  if (prop === "email") isEmailValid.value = isValid;
};

const logo = ref(new URL("../../assets/logo.png", import.meta.url).href);
const loginImage = ref(new URL("../../assets/images/login-image.svg", import.meta.url).href);

const userForgotData = ref<UserForgotForm>({
  username: "",
  password: "",
  password_repeat: "",
  email: "",
  code: "",
});

// 用户名校验规则
const validateUsername = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else if (!/^[\u4e00-\u9fa5a-zA-Z0-9]+$/.test(value)) {
    callback(new Error("用户名不能包含特殊字符，只能是中文/英文"));
  } else {
    callback();
  }
};

// 重复密码校验规则
const validatePasswordRepeat = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== userForgotData.value.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const loginRules = computed(() => {
  return {
    username: [
      { validator: validateUsername, trigger: ["blur", "change"] }, // 修改或失去焦点时触发
      { min: 4, max: 12, message: "用户名的长度必须在4-12个字符之间", trigger: ["blur", "change"] },
    ],
    password: [
      {
        required: true,
        message: "请输入密码",
        trigger: ["blur", "change"],
      },
      { min: 6, max: 15, message: "密码的长度必须在6-15个字符之间", trigger: ["blur", "change"] },
    ],
    password_repeat: [{ validator: validatePasswordRepeat, trigger: ["blur", "change"] }],
    email: [
      { required: true, message: "请输入邮件地址", trigger: ["blur", "change"] },
      { type: "email", message: "请输入合法的电子邮件地址", trigger: ["blur", "change"] },
    ],
    code: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

const validateEmail = () => {
  if (!userForgotData.value.email) {
    ElMessage.error("请输入邮箱");
    return;
  }

  // 验证邮箱格式
  const reg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
  if (!reg.test(userForgotData.value.email)) {
    ElMessage.error("邮箱格式不正确");
    return;
  }

  UserAPI.sendVerificationCode(userForgotData.value.email, "FORGOT_EMAIL").then(() => {
    ElMessage.success("发送邮箱验证码成功");
  });

  emailCountdown.value = 60;
  emailTimer.value = setInterval(() => {
    if (emailCountdown.value > 0) {
      emailCountdown.value -= 1;
    } else {
      clearInterval(emailTimer.value!);
    }
  }, 1000);
};
// 注册
async function handleForgotSubmit() {
  forgotFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        await UserAPI.userForgot(userForgotData.value);
        ElMessage.success("密码重置成功");
        await router.push({ path: "/login" });
      } catch (error) {
        console.error("Error during registration:", error);
        ElMessage.error("密码重置失败");
      } finally {
        loading.value = false;
      }
    }
  });
}

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

// 主题切换
const toggleTheme = () => {
  const newTheme = settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

// 检查输入大小写
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

onMounted(() => {
  //
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background: url("@/assets/images/login-background-light.jpg") no-repeat center right;

  .login-header {
    position: absolute;
    top: 0;
    display: flex;
    justify-content: right;
    width: 100%;
    padding: 15px;

    .logo {
      width: 26px;
      height: 26px;
    }

    .title {
      margin: auto 5px;
      font-size: 24px;
      font-weight: bold;
      color: #3b82f6;
    }
  }

  .login-content {
    display: flex;
    width: 960px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: var(--el-box-shadow-light);

    @media (width <= 768px) {
      flex-direction: column;
      max-width: 100%;
      height: 100vh;
      padding: 0 30px;
      border-radius: 0;
      box-shadow: none;
    }

    .login-img {
      display: flex;
      flex: 3;
      align-items: center;
      justify-content: center;
      background: linear-gradient(60deg, #165dff, #6aa1ff);

      @media (width <= 768px) {
        display: none;
      }
    }

    .login-form {
      display: flex;
      flex: 2;
      flex-direction: column;
      justify-content: center;
      min-width: 400px;
      padding: 30px;

      @media (width <= 768px) {
        width: 100%;
        padding: 0 20px;
      }

      .form-title {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 0 20px;
        text-align: center;
      }

      .input-wrapper {
        display: flex;
        align-items: center;
        width: 100%;
      }

      .captcha-img {
        height: 48px;
        cursor: pointer;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
      }

      .third-party-login {
        display: flex;
        justify-content: center;
        width: 100%;
        color: var(--el-text-color-secondary);

        *:not(:first-child) {
          margin-left: 20px;
        }

        .icon {
          cursor: pointer;
        }
      }
    }
  }

  .login-footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
  }
}

:deep(.el-form-item) {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

html.dark {
  .login {
    background: url("@/assets/images/login-background-dark.jpg") no-repeat center right;

    .login-content {
      background: transparent;
      box-shadow: var(--el-box-shadow);
    }
  }
}
</style>
